﻿using System;
using System.IO;
using System.Windows.Forms;

namespace MyVocabulary.Popup
{
    public partial class AddNewFile : Form
    {
        #region Const

        protected static class FormMessages
        {
            public const string InvalidNameErrorMsg = "Please enter a valid name";
            public const string DuplicateNameErrorMsg = "A file with this name already exists";
            public const string GeneralErrorMsg = "Error creating file";
        }

        #endregion

        protected string parentFolder;

        public FileInfo CreatedFile;
        public event EventHandler OnNewFileCreated;

        public AddNewFile(string parentFolder)
        {
            this.parentFolder = parentFolder;
            InitializeComponent();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {            
            if(tbName.Text.Length == 0)
            {
                lbError.Text = FormMessages.InvalidNameErrorMsg;
                toolTip1.SetToolTip(lbError, FormMessages.InvalidNameErrorMsg);
                return;                
            }

            try
            {
                var fileName = tbName.Text + (rblVocabulary.Checked ? ".xml" : ".vml");
                var dir = new DirectoryInfo(parentFolder);
                //check if the file already exists
                foreach (var file in dir.GetFiles())
                {
                    if (string.Compare(file.Name, fileName, true) != 0) 
                        continue;

                    lbError.Text = FormMessages.DuplicateNameErrorMsg;
                    toolTip1.SetToolTip(lbError, FormMessages.DuplicateNameErrorMsg);
                    return;
                }

                //create the file
                CreatedFile = new FileInfo(string.Format("{0}\\{1}", dir.FullName, fileName));
                var fs = CreatedFile.Create();
                var writer = new StreamWriter(fs);
                writer.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>");
                writer.WriteLine("<DocumentElement>");
                writer.WriteLine("</DocumentElement>");
                writer.Flush();
                writer.Close();
                fs.Close();
                if (OnNewFileCreated != null)
                    OnNewFileCreated(this, null);
                Close();
            }
            catch (Exception exp)
            {
                lbError.Text = FormMessages.GeneralErrorMsg;
                toolTip1.SetToolTip(lbError,exp.Message);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}